package book;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试notify执行后，不是马上释放锁，而且等synchronized执行完才释放锁
 * 而wait和sleep后，会释放锁的控制
 * @author：涂有
 * @date 2017年2月28日 下午4:00:19
 */
public class WaitNotifyTest2 {
	
	static class A implements Runnable{
		
		List<Integer> lock;
		
		public A(List<Integer> lock){
			
			this.lock = lock;
		}

		@Override
		public void run() {

			synchronized (lock) {

				for(int i = 0; i < 10; i++){
					
					lock.add(i);
					System.out.println(lock);
					if(lock.size() == 5){
						
						lock.notify();
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	static class B implements Runnable{
		
		List<Integer> lock;
		
		public B(List<Integer> lock){
			
			this.lock = lock;
		}
		
		@Override
		public void run() {
			
			synchronized (lock) {
				
				if(lock.size() != 5){
					
					System.out.println("开始等待");
					try {
						lock.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("结束等待");
			}
		}
	}

	public static void main(String[] args) {
		
		List<Integer> list = new ArrayList<Integer>();
		A a = new A(list);
		Thread a1 = new Thread(a);
		Thread b1 = new Thread(new B(list));
		
		b1.start();
		a1.start();
	}
}
